<template>
  <div class="system-settings">
    <h1 class="page-title">系统设置</h1>
    
    <el-card class="settings-card">
      <el-tabs v-model="activeTab">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <el-form :model="basicSettings" label-width="120px" v-loading="loading.basic">
            <el-form-item label="系统名称">
              <el-input v-model="basicSettings.systemName" placeholder="请输入系统名称" />
            </el-form-item>
            
            <el-form-item label="系统Logo">
              <el-upload
                class="logo-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleLogoSuccess"
                :before-upload="beforeLogoUpload"
              >
                <img v-if="basicSettings.logoUrl" :src="basicSettings.logoUrl" class="logo" />
                <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="logo-tip">建议尺寸: 200px × 60px</div>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveSettings('basic')">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 系统信息 -->
        <el-tab-pane label="系统信息" name="system">
          <el-descriptions :column="1" border v-loading="loading.system">
            <el-descriptions-item label="系统版本">
              {{ systemInfo.version }}
            </el-descriptions-item>
            <el-descriptions-item label="许可证信息">
              {{ systemInfo.license }}
            </el-descriptions-item>
            <el-descriptions-item label="系统资源">
              <div class="resource-info">
                <el-progress
                  type="dashboard"
                  :percentage="systemResources.cpuUsage"
                  :color="getResourceColor(systemResources.cpuUsage)"
                >
                  <template #default>
                    <div class="progress-label">
                      <div>CPU</div>
                      <div>{{ formatUsage(systemResources.cpuUsage) }}</div>
                    </div>
                  </template>
                </el-progress>
                
                <el-progress
                  type="dashboard"
                  :percentage="systemResources.memoryUsage"
                  :color="getResourceColor(systemResources.memoryUsage)"
                >
                  <template #default>
                    <div class="progress-label">
                      <div>内存</div>
                      <div>{{ formatUsage(systemResources.memoryUsage) }}</div>
                    </div>
                  </template>
                </el-progress>
                
                <el-progress
                  type="dashboard"
                  :percentage="systemResources.diskUsage"
                  :color="getResourceColor(systemResources.diskUsage)"
                >
                  <template #default>
                    <div class="progress-label">
                      <div>磁盘</div>
                      <div>{{ formatUsage(systemResources.diskUsage) }}</div>
                    </div>
                  </template>
                </el-progress>
              </div>
              <div class="refresh-button">
                <el-button type="primary" size="small" @click="fetchSystemResources" :loading="loading.resources">
                  <el-icon><Refresh /></el-icon> 刷新
                </el-button>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        
        <!-- 外部系统集成 -->
        <el-tab-pane label="外部系统集成" name="integration">
          <el-collapse v-loading="loading.integration">
            <!-- 第三方平台API对接 -->
            <el-collapse-item title="第三方平台API对接" name="api">
              <el-form :model="integrationSettings.api" label-width="120px">
                <el-form-item label="API地址">
                  <el-input v-model="integrationSettings.api.url" placeholder="请输入API地址" />
                </el-form-item>
                <el-form-item label="API密钥">
                  <el-input v-model="integrationSettings.api.key" placeholder="请输入API密钥" show-password />
                </el-form-item>
                <el-form-item label="API状态">
                  <el-switch v-model="integrationSettings.api.enabled" />
                </el-form-item>
              </el-form>
            </el-collapse-item>
            
            <!-- 打印机配置 -->
            <el-collapse-item title="打印机配置" name="printer">
              <el-form :model="integrationSettings.printer" label-width="120px">
                <el-form-item label="打印机名称">
                  <el-input v-model="integrationSettings.printer.name" placeholder="请输入打印机名称" />
                </el-form-item>
                <el-form-item label="打印机IP">
                  <el-input v-model="integrationSettings.printer.ip" placeholder="请输入打印机IP" />
                </el-form-item>
                <el-form-item label="打印机端口">
                  <el-input-number v-model="integrationSettings.printer.port" :min="1" :max="65535" />
                </el-form-item>
                <el-form-item label="打印机状态">
                  <el-switch v-model="integrationSettings.printer.enabled" />
                </el-form-item>
              </el-form>
            </el-collapse-item>
            
            <!-- 热敏打印报表配置 -->
            <el-collapse-item title="热敏打印报表配置" name="receipt">
              <el-form :model="integrationSettings.receipt" label-width="120px">
                <el-form-item label="页眉内容">
                  <el-input v-model="integrationSettings.receipt.header" type="textarea" :rows="2" />
                </el-form-item>
                <el-form-item label="页脚内容">
                  <el-input v-model="integrationSettings.receipt.footer" type="textarea" :rows="2" />
                </el-form-item>
                <el-form-item label="字体大小">
                  <el-select v-model="integrationSettings.receipt.fontSize">
                    <el-option label="小" value="small" />
                    <el-option label="中" value="medium" />
                    <el-option label="大" value="large" />
                  </el-select>
                </el-form-item>
                <el-form-item label="显示商品图片">
                  <el-switch v-model="integrationSettings.receipt.showImage" />
                </el-form-item>
              </el-form>
            </el-collapse-item>
          </el-collapse>
          
          <div class="form-actions">
            <el-button type="primary" @click="saveSettings('integration')">保存设置</el-button>
          </div>
        </el-tab-pane>

        <!-- 系统维护 -->
        <el-tab-pane label="系统维护" name="maintenance">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>服务状态</span>
                <el-button type="text" @click="refreshSystemStatus">
                  <el-icon><Refresh /></el-icon> 刷新
                </el-button>
              </div>
            </template>
            <div v-loading="loading.status">
              <div class="system-info">
                <p><strong>系统时间:</strong> {{ formatDateTime(systemStatus.systemTime) }}</p>
                <p><strong>系统版本:</strong> {{ systemStatus.version }}</p>
              </div>
              <el-table :data="systemStatus.containers" style="width: 100%; margin-top: 15px;">
                <el-table-column prop="name" label="服务名称" />
                <el-table-column prop="status" label="状态" />
                <el-table-column label="运行状态">
                  <template #default="scope">
                    <el-tag :type="scope.row.isRunning ? 'success' : 'danger'">
                      {{ scope.row.isRunning ? '运行中' : '已停止' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
          
          <el-card class="box-card" style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <span>服务重启</span>
                <el-alert
                  type="warning"
                  title="注意"
                  description="重启服务可能会导致短暂的服务不可用，请谨慎操作"
                  show-icon
                  :closable="false"
                  style="margin-top: 10px"
                />
              </div>
            </template>
            <div class="service-info">
              <el-descriptions border :column="1">
                <el-descriptions-item label="前台服务">
                  <el-tag :type="getServiceStatus('hello-beer-frontend')">
                    {{ getServiceStatusText('hello-beer-frontend') }}
                  </el-tag>
                  <span class="service-description">负责用户界面渲染和交互</span>
                </el-descriptions-item>
                <el-descriptions-item label="后台服务">
                  <el-tag :type="getServiceStatus('hello-beer-backend')">
                    {{ getServiceStatusText('hello-beer-backend') }}
                  </el-tag>
                  <span class="service-description">负责API接口和业务逻辑处理</span>
                </el-descriptions-item>
                <el-descriptions-item label="网关服务">
                  <el-tag :type="getServiceStatus('hello-beer-nginx')">
                    {{ getServiceStatusText('hello-beer-nginx') }}
                  </el-tag>
                  <span class="service-description">负责HTTP请求路由和重启所有服务</span>
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <div class="service-restart-buttons">
              <el-button 
                type="primary" 
                @click="restartService('frontend')" 
                :loading="loading.frontend"
              >
                重启前台服务
              </el-button>
              <el-button 
                type="warning" 
                @click="restartService('backend')" 
                :loading="loading.backend"
              >
                重启后台服务
              </el-button>
              <el-button 
                type="danger" 
                @click="restartService('nginx')" 
                :loading="loading.nginx"
              >
                重启所有服务
              </el-button>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Refresh } from '@element-plus/icons-vue';
import { getSettingsByCategory, updateSettings } from '@/api/systemSettings';
import { restartFrontend, restartBackend, restartNginx, getSystemStatus, getSystemResources } from '@/api/system';

export default {
  name: 'SystemSettings',
  components: {
    Plus,
    Refresh
  },
  setup() {
    // 当前激活的标签页
    const activeTab = ref('basic');
    
    // 加载状态
    const loading = reactive({
      basic: false,
      system: false,
      integration: false,
      frontend: false,
      backend: false,
      nginx: false,
      status: false,
      resources: false
    });
    
    // 基本设置
    const basicSettings = reactive({
      systemName: '哈喽啤鲜生收银与库存管理系统',
      logoUrl: ''
    });
    
    // 系统信息
    const systemInfo = reactive({
      version: '1.0.0',
      license: 'MIT'
    });
    
    // 系统资源使用情况
    const systemResources = reactive({
      cpuUsage: null,
      memoryUsage: null,
      diskUsage: null
    });
    
    // 资源刷新定时器
    let resourceTimer = null;
    
    // 获取系统资源使用情况
    const fetchSystemResources = async () => {
      loading.resources = true;
      try {
        const response = await getSystemResources();
        if (response.data && response.data.success) {
          systemResources.cpuUsage = response.data.data.cpuUsage;
          systemResources.memoryUsage = response.data.data.memoryUsage;
          systemResources.diskUsage = response.data.data.diskUsage;
        } else {
          ElMessage.error('获取系统资源使用情况失败');
        }
      } catch (error) {
        console.error('获取系统资源使用情况失败:', error);
        ElMessage.error('获取系统资源使用情况失败');
      } finally {
        loading.resources = false;
      }
    };
    
    // 外部系统集成设置
    const integrationSettings = reactive({
      api: {
        url: '',
        key: '',
        enabled: false
      },
      printer: {
        name: '',
        ip: '',
        port: 9100,
        enabled: false
      },
      receipt: {
        header: '哈喽啤鲜生国贸店',
        footer: '谢谢惠顾，欢迎再次光临！',
        fontSize: 'medium',
        showImage: true
      }
    });
    
    // 系统状态数据
    const systemStatus = reactive({
      containers: [],
      systemTime: '',
      version: ''
    });
    
    // 获取资源使用颜色
    const getResourceColor = (percentage) => {
      if (percentage < 50) return '#67c23a';
      if (percentage < 80) return '#e6a23c';
      return '#f56c6c';
    };
    
    // 加载设置
    const loadSettings = async (category) => {
      loading[category] = true;
      try {
        const response = await getSettingsByCategory(category);
        if (response.success) {
          const data = response.data;
          
          if (category === 'basic') {
            basicSettings.systemName = data.systemName?.value || basicSettings.systemName;
            basicSettings.logoUrl = data.logoUrl?.value || basicSettings.logoUrl;
          } else if (category === 'system') {
            systemInfo.version = data.version?.value || systemInfo.version;
            systemInfo.license = data.license?.value || systemInfo.license;
          } else if (category === 'integration') {
            // API设置
            integrationSettings.api.url = data['api.url']?.value || integrationSettings.api.url;
            integrationSettings.api.key = data['api.key']?.value || integrationSettings.api.key;
            integrationSettings.api.enabled = data['api.enabled']?.value === 'true';
            
            // 打印机设置
            integrationSettings.printer.name = data['printer.name']?.value || integrationSettings.printer.name;
            integrationSettings.printer.ip = data['printer.ip']?.value || integrationSettings.printer.ip;
            integrationSettings.printer.port = parseInt(data['printer.port']?.value) || integrationSettings.printer.port;
            integrationSettings.printer.enabled = data['printer.enabled']?.value === 'true';
            
            // 热敏打印设置
            integrationSettings.receipt.header = data['receipt.header']?.value || integrationSettings.receipt.header;
            integrationSettings.receipt.footer = data['receipt.footer']?.value || integrationSettings.receipt.footer;
            integrationSettings.receipt.fontSize = data['receipt.fontSize']?.value || integrationSettings.receipt.fontSize;
            integrationSettings.receipt.showImage = data['receipt.showImage']?.value === 'true';
          }
        }
      } catch (error) {
        console.error(`加载${category}设置失败:`, error);
        ElMessage.error(`加载${category}设置失败`);
      } finally {
        loading[category] = false;
      }
    };
    
    // 保存设置
    const saveSettings = async (category) => {
      loading[category] = true;
      try {
        let settingsData = {};
        
        if (category === 'basic') {
          settingsData = {
            systemName: basicSettings.systemName,
            logoUrl: basicSettings.logoUrl
          };
        } else if (category === 'integration') {
          settingsData = {
            'api.url': integrationSettings.api.url,
            'api.key': integrationSettings.api.key,
            'api.enabled': String(integrationSettings.api.enabled),
            'printer.name': integrationSettings.printer.name,
            'printer.ip': integrationSettings.printer.ip,
            'printer.port': String(integrationSettings.printer.port),
            'printer.enabled': String(integrationSettings.printer.enabled),
            'receipt.header': integrationSettings.receipt.header,
            'receipt.footer': integrationSettings.receipt.footer,
            'receipt.fontSize': integrationSettings.receipt.fontSize,
            'receipt.showImage': String(integrationSettings.receipt.showImage)
          };
        }
        
        const response = await updateSettings(category, settingsData);
        if (response.success) {
          ElMessage.success('设置保存成功');
        } else {
          ElMessage.error('设置保存失败');
        }
      } catch (error) {
        console.error(`保存${category}设置失败:`, error);
        ElMessage.error(`保存${category}设置失败`);
      } finally {
        loading[category] = false;
      }
    };
    
    // Logo上传相关方法
    const handleLogoSuccess = (response, file) => {
      basicSettings.logoUrl = response.data.url;
      ElMessage.success('Logo上传成功');
    };
    
    const beforeLogoUpload = (file) => {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      
      if (!isImage) {
        ElMessage.error('Logo必须是图片格式!');
        return false;
      }
      if (!isLt2M) {
        ElMessage.error('Logo大小不能超过2MB!');
        return false;
      }
      return true;
    };
    
    // 获取系统状态
    const refreshSystemStatus = async () => {
      loading.status = true;
      try {
        const res = await getSystemStatus();
        if (res.data && res.data.success) {
          systemStatus.containers = res.data.data.containers || [];
          systemStatus.systemTime = res.data.data.systemTime || '';
          systemStatus.version = res.data.data.version || '';
        } else {
          ElMessage.error('获取系统状态失败');
        }
      } catch (error) {
        console.error('获取系统状态失败:', error);
        ElMessage.error('获取系统状态失败');
      } finally {
        loading.status = false;
      }
    };
    
    // 格式化日期时间
    const formatDateTime = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    };
    
    // 获取服务状态类型
    const getServiceStatus = (serviceName) => {
      const container = systemStatus.containers.find(c => c.name === serviceName);
      if (!container) return 'info';
      return container.isRunning ? 'success' : 'danger';
    };
    
    // 获取服务状态文本
    const getServiceStatusText = (serviceName) => {
      const container = systemStatus.containers.find(c => c.name === serviceName);
      if (!container) return '未知';
      return container.isRunning ? '运行中' : '已停止';
    };
    
    // 重启服务
    const restartService = async (service) => {
      ElMessageBox.confirm(`确定要重启${service === 'frontend' ? '前台' : service === 'backend' ? '后台' : '所有'}服务吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        loading[service] = true;
        try {
          let res;
          if (service === 'frontend') {
            res = await restartFrontend();
          } else if (service === 'backend') {
            res = await restartBackend();
          } else if (service === 'nginx') {
            res = await restartNginx();
          }
          
          if (res.data && res.data.success) {
            ElMessage.success(`${service === 'frontend' ? '前台' : service === 'backend' ? '后台' : '所有'}服务重启成功`);
            // 延迟刷新状态，等待服务重启完成
            setTimeout(() => {
              refreshSystemStatus();
            }, 5000);
          } else {
            ElMessage.error(`重启${service === 'frontend' ? '前台' : service === 'backend' ? '后台' : '所有'}服务失败`);
          }
        } catch (error) {
          console.error(`重启${service}服务失败:`, error);
          ElMessage.error(`重启${service === 'frontend' ? '前台' : service === 'backend' ? '后台' : '所有'}服务失败`);
        } finally {
          loading[service] = false;
        }
      }).catch(() => {});
    };
    
    // 格式化资源使用率显示
    const formatUsage = (value) => {
      return value === null || value === undefined ? '--' : `${value}%`;
    };
    
    // 初始化
    onMounted(() => {
      loadSettings('basic');
      loadSettings('system');
      loadSettings('integration');
      
      // 如果当前标签页是系统维护，获取系统状态
      if (activeTab.value === 'maintenance') {
        refreshSystemStatus();
      }
      
      // 获取系统资源使用情况
      fetchSystemResources();
      
      // 设置定时刷新系统资源的计时器（每30秒刷新一次）
      resourceTimer = setInterval(fetchSystemResources, 30000);
    });
    
    // 监听标签页变化
    const handleTabChange = (tab) => {
      if (tab === 'maintenance') {
        refreshSystemStatus();
      } else if (tab === 'system') {
        // 切换到系统信息标签页时刷新资源数据
        fetchSystemResources();
      }
    };
    
    // 在组件卸载时清除定时器
    onUnmounted(() => {
      if (resourceTimer) {
        clearInterval(resourceTimer);
        resourceTimer = null;
      }
    });
    
    return {
      activeTab,
      loading,
      basicSettings,
      systemInfo,
      systemResources,
      integrationSettings,
      systemStatus,
      getResourceColor,
      saveSettings,
      handleLogoSuccess,
      beforeLogoUpload,
      refreshSystemStatus,
      formatDateTime,
      getServiceStatus,
      getServiceStatusText,
      restartService,
      handleTabChange,
      fetchSystemResources,
      formatUsage
    };
  }
};
</script>

<style scoped>
.system-settings {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: 500;
}

.settings-card {
  margin-bottom: 20px;
}

.logo-uploader {
  width: 200px;
  height: 60px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo-uploader:hover {
  border-color: #409eff;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.logo-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.resource-info {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
}

.progress-label {
  text-align: center;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
}

.service-restart-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.card-header {
  display: flex;
  flex-direction: column;
}

.service-info {
  margin-bottom: 20px;
}

.service-description {
  margin-left: 10px;
  color: #606266;
}

.system-info {
  margin-bottom: 20px;
}

.refresh-button {
  margin-top: 10px;
  text-align: right;
}
</style> 